﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;

namespace HardToolApp.Tool
{
    internal class SocketComm
    {
        public UInt16 port { get; set; } = 5566;
        public AsyncSocketTCPServer tcpServer { get; set; }
        public SocketComm() 
        {
            while(PortInUse(port))
            {
                port++;
            }
            IPAddress address;
            IPAddress.TryParse("127.0.0.1", out address);
            tcpServer = new AsyncSocketTCPServer(new IPEndPoint(address, port));
            tcpServer.Start();
        }
       
        public bool PortInUse(int port)
        {
            bool inUse = false;

            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }

            return inUse;
        }
    }
}
